package com.ayu.commentbackend;

import com.ayu.commentbackend.mapper.UserMapper;
import com.ayu.commentbackend.properties.JwtProperties;
import com.ayu.commentbackend.utils.JwtUtil;
import com.ayu.commentbackend.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(jwtProperties.getUserTokenName());

        try{
            // 解密，如果报错说明jwt被修改了
            Map<String, Object> claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);

            // 验证token版本
            Long userId = Long.valueOf(claims.get("userId").toString());  // 此处不能使用强制类型转换
            Integer tokenVersion = (Integer) claims.get("version");
            if(userMapper.getTokenVersionById(userId) != tokenVersion){
                log.error("此token已失效，因为它的版本落后于数据库");
                response.setStatus(401);
                return false;
            }

            ThreadLocalUtil.setCurrentId(userId);
            return true;
        }catch (Exception e){
            // 401：未授权
            log.error(e.getMessage());
            response.setStatus(401);
            return false;
        }

    }
}
